package com.lizk.net.http.tools;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Get {
	public static String get(String url,Params params) throws Exception {
		
		HttpClient client = HttpClients.createDefault();
		HttpEntity entity = null;
		if(params != null) {
			try {
				entity = new UrlEncodedFormEntity(params,"utf-8");
				
				url = url +"?" +EntityUtils.toString(entity);
				
				System.out.println("访问链接为" + url);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new Exception ("参数格式化失败",e);
			} catch (ParseException e) {
				e.printStackTrace();
				throw new Exception ("参数格式化失败",e);
			} catch (IOException e) {
				e.printStackTrace();
				throw new Exception ("参数格式化失败",e);
			}
		}
		
		HttpGet get  = new HttpGet(url);
		
		try {
			HttpResponse response = client.execute(get);
			HttpEntity resultEntity = response.getEntity();
			return EntityUtils.toString(resultEntity);
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception ("访问网页失败",e);
		}
		
	}
}
